package com.vcens.yzpay.service;

import com.alibaba.fastjson.JSONObject;
import com.vcens.yzpay.config.YzConfig;
import com.vcens.yzpay.utils.HttpRequest;
import com.youzan.open.sdk.client.auth.Token;
import com.youzan.open.sdk.client.core.DefaultYZClient;
import com.youzan.open.sdk.client.core.YZClient;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanPayQrcodeCreate;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanPayQrcodeCreateParams;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanPayQrcodeCreateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author BY VeChar
 * @CreateTime 2018/8/16 13:47
 * @Description TODO
 */
@Service
public class PayServiceImpl implements IPayService {

    @Autowired
    private YzConfig yzConfig;

    /**
     * 有赞的SDK拿到的令牌总是无效，所以就手动实现
     * @return
     */
    @Override
    public JSONObject getAccessToken() {
        Map<String, String> params = new HashMap<>();
        //有赞云颁发给开发者的应用ID,上一步 “申请应用” 时获得
        params.put("client_id", yzConfig.getClientId());
        //返回的令牌类型（固定为 “code”）
        params.put("client_secret", yzConfig.getClientSecret());
        //自定义字段，用于保持请求和回调的状态，在回调时，会回传该参数。开发者可以用这个参数验证请求有效性，
        // 也可以记录用户请求授权页前的位置。可防止CSRF攻击
        params.put("grant_type", yzConfig.getGrantType());
        //授权店铺ID
        params.put("kdt_id", yzConfig.getKdtId());
        //请求响应
        String s = HttpRequest.httpPost(
                yzConfig.getUrl(), null, params, "UTF-8");

        if (null != s) {
            System.out.println(s);
            return JSONObject.parseObject(s);
        }

        return null;
    }

    @Override
    public YouzanPayQrcodeCreateResult createQrInfo(Token token, Map<String, String> payInfo) throws Exception {
        YZClient client = new DefaultYZClient(token);
        YouzanPayQrcodeCreateParams youzanPayQrcodeCreateParams = new YouzanPayQrcodeCreateParams();
        youzanPayQrcodeCreateParams.setQrName(payInfo.get("payReason"));
        youzanPayQrcodeCreateParams.setQrPrice(payInfo.get("amount"));
        youzanPayQrcodeCreateParams.setQrType(payInfo.get("qr_type"));
        YouzanPayQrcodeCreate youzanPayQrcodeCreate = new YouzanPayQrcodeCreate();
        youzanPayQrcodeCreate.setAPIParams(youzanPayQrcodeCreateParams);
        YouzanPayQrcodeCreateResult result = client.invoke(youzanPayQrcodeCreate);
        return result;
    }
}
